class SingletonLazy {
    private volatile SingletonLazy instance;

    private SingletonLazy() {}

    public SingletonLazy getInstance() {
        if(instance == null) {
            synchronized (this) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }
}

class MyBlockingQueue {
    private int[] elem;
    private int size;
    private int head;
    private int tail;

    public MyBlockingQueue(int capacity) {
        elem = new int[capacity];
    }

    public synchronized void put(int x) throws InterruptedException {
        while(size == elem.length) {
            this.wait();
        }
        elem[tail] = x;
        tail++;
        if(tail == elem.length) {
            tail = 0;
        }
        size++;
        this.notify();
    }

    public synchronized int take() throws InterruptedException {
        while(size == 0) {
            this.wait();
        }
        int ret = elem[head];
        head++;
        if(head == elem.length) {
            head = 0;
        }
        size--;
        this.notify();
        return ret;
    }
}

public class Demo5 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(10);
        Thread producer = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                int id = i;
                try {
                    queue.put(i);
                    System.out.println("生产元素" + id);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                int id = i;
                try {
                    int ret = queue.take();
                    Thread.sleep(10);
                    System.out.println("消费元素" + ret);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        producer.start();
        consumer.start();
    }
}
